package com.bml.architect.algorithms.standard;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.math.BigInteger;
import java.util.Collection;

public class MyPreciseTableAlgorithm implements PreciseShardingAlgorithm<Long> {
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> preciseShardingValue) {
        //逻辑表名称 如：course
        String logicTableName = preciseShardingValue.getLogicTableName();
        //分片健 如cid
        String columnName = preciseShardingValue.getColumnName();
        //值，比如select * from course where cid=3，这里的value就是3
        Long value = preciseShardingValue.getValue();

        BigInteger shardingvalue = BigInteger.valueOf(value);
        BigInteger val = shardingvalue.mod(new BigInteger("2")).add(new BigInteger("1"));

        String key = logicTableName+"_"+val;
        if(availableTargetNames.contains(key)){
            return key;
        }
        //couse_1, course_2
        throw new UnsupportedOperationException("route "+ key +" is not supported ,please check your config");
    }
}
